import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';

import { prisma, dbOperation } from '@/lib/db';
import { sendEmail } from '@/lib/email';
import crypto from 'crypto';

// 创建项目邀请
export async function POST(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 解析请求体
    let body;
    try {
      body = await request.json();
      console.log('收到的邀请请求体:', body);
    } catch (parseError) {
      console.error('解析请求体失败:', parseError);
      return NextResponse.json(
        { success: false, message: '无效的请求格式', error: 'JSON解析失败' },
        { status: 400 }
      );
    }
    
    const { projectId, email, role = 'MEMBER', message } = body;

    if (!projectId) {
      console.error('缺少必填参数: projectId');
      return NextResponse.json(
        { success: false, message: '缺少必填参数: projectId' },
        { status: 400 }
      );
    }
    
    if (!email) {
      console.error('缺少必填参数: email');
      return NextResponse.json(
        { success: false, message: '缺少必填参数: email' },
        { status: 400 }
      );
    }

    // 验证角色是否有效
    const validRoles = ['ADMIN', 'MEMBER', 'VIEWER'];
    if (!validRoles.includes(role)) {
      console.error('无效的角色类型:', role);
      return NextResponse.json(
        { success: false, message: `无效的角色类型: ${role}` },
        { status: 400 }
      );
    }

    // 验证用户是否有权限发送邀请
    console.log('验证用户权限:', session.user.id, projectId);
    const userRole = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: session.user.id,
          role: {
            in: ['OWNER', 'ADMIN'],
          },
        },
        include: {
          project: {
            select: {
              name: true,
            },
          },
        },
      });
    });

    if (!userRole.success) {
      console.error('查询用户权限失败:', userRole.error);
    }

    if (!userRole.success || !userRole.data) {
      return NextResponse.json(
        { success: false, message: '您没有权限邀请项目成员' },
        { status: 403 }
      );
    }

    // 检查邮箱是否已注册
    const existingUser = await dbOperation(async () => {
      return prisma.user.findUnique({
        where: {
          email,
        },
      });
    });

    if (!existingUser.success) {
      return NextResponse.json(
        { success: false, message: '查找用户失败', error: existingUser.error },
        { status: 500 }
      );
    }

    // 如果用户已存在，检查是否已经是项目成员
    if (existingUser.data) {
      const existingMember = await dbOperation(async () => {
        return prisma.projectUser.findFirst({
          where: {
            projectId,
            userId: existingUser.data?.id || '', // 添加空字符串作为回退值
          },
        });
      });

      if (!existingMember.success) {
        return NextResponse.json(
          { success: false, message: '检查用户关系失败', error: existingMember.error },
          { status: 500 }
        );
      }

      if (existingMember.data) {
        return NextResponse.json(
          { success: false, message: '该用户已经是项目成员' },
          { status: 400 }
        );
      }
    }

    // 生成邀请链接的令牌
    const token = crypto.randomBytes(32).toString('hex');
    const expires = new Date();
    expires.setHours(expires.getHours() + 48); // 邀请链接48小时有效

    // 创建项目邀请记录
    const invite = await dbOperation(async () => {
      return prisma.projectInvite.create({
        data: {
          projectId,
          email,
          role,
          token,
          expires,
          inviterId: session.user.id,
          message: message || '',
        },
      });
    });

    if (!invite.success || !invite.data) {
      return NextResponse.json(
        { 
          success: false, 
          message: '创建邀请失败', 
          error: invite.error || '无法获取邀请数据'
        },
        { status: 500 }
      );
    }

    // 此时我们确保invite.data存在
    const inviteData = invite.data;

    // 构建邀请链接
    const baseUrl = process.env.NEXTAUTH_URL || 'http://localhost:3000';
    const inviteUrl = `${baseUrl}/project/invite/accept?token=${token}`;

    // 发送邀请邮件
    const projectName = userRole.data.project?.name || '项目';
    const inviterName = session.user.name || '项目成员';
    const roleText = role === 'ADMIN' ? '管理员' : role === 'MEMBER' ? '成员' : '观察者';

    let emailSent = false;
    let emailErrorMsg = null;

    try {
      console.log('准备发送邮件:', {
        to: email,
        subject: `您被邀请加入项目「${projectName}」`,
        hasMessage: !!message,
        inviteUrl: inviteUrl
      });

      const emailResult = await sendEmail({
        to: email,
        subject: `您被邀请加入项目「${projectName}」`,
        text: `项目邀请：${inviterName} 邀请您作为${roleText}加入项目「${projectName}」${message ? `\n留言：${message}` : ''}\n\n请点击下方链接接受邀请（链接48小时内有效）：\n${inviteUrl}\n\n如果链接无法点击，请复制粘贴到浏览器地址栏中打开。`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
            <h2 style="color: #333;">项目邀请</h2>
            <p>${inviterName} 邀请您作为<strong>${roleText}</strong>加入项目「<strong>${projectName}</strong>」</p>
            ${message ? `<div style="background: #f5f5f5; padding: 15px; border-radius: 5px; margin: 15px 0;"><p><strong>留言：</strong>${message}</p></div>` : ''}
            <p>请点击下方按钮接受邀请（链接48小时内有效）：</p>
            <div style="text-align: center; margin: 30px 0;">
              <a href="${inviteUrl}" 
                 style="background-color: #007bff; color: white; padding: 12px 30px; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;"
                 target="_blank">
                接受邀请
              </a>
            </div>
            <div style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 5px; margin: 20px 0;">
              <p style="margin: 0; color: #856404; font-size: 14px;">
                <strong>注意：</strong>如果点击按钮无法直接跳转，请复制以下链接到浏览器地址栏中打开：
              </p>
              <p style="margin: 10px 0 0 0; word-break: break-all; background: #f8f9fa; padding: 10px; border-radius: 3px; font-family: monospace; font-size: 12px;">
                ${inviteUrl}
              </p>
            </div>
            <hr style="margin: 30px 0; border: none; border-top: 1px solid #eee;">
            <p style="color: #999; font-size: 12px;">
              此邮件由 NextCollab 系统自动发送，请勿回复。
            </p>
          </div>
        `
      });

      emailSent = true;
    } catch (emailError) {
      console.error('发送邮件失败:', emailError);
      emailErrorMsg = emailError.message;
    }

    return NextResponse.json(
      {
        success: true,
        message: emailSent ? '邀请已发送' : '邀请已创建，但邮件发送失败',
        emailSent,
        emailError: emailErrorMsg,
        data: {
          id: inviteData.id,
          email: inviteData.email,
          role: inviteData.role,
          expires: inviteData.expires,
          inviteUrl,
        },
      },
      { status: 201 }
    );
  } catch (error: any) {
    console.error('发送项目邀请失败:', error);
    return NextResponse.json(
      { success: false, message: '发送项目邀请失败', error: error.message },
      { status: 500 }
    );
  }
}

// 获取项目邀请列表
export async function GET(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const projectId = searchParams.get('projectId');

    if (!projectId) {
      return NextResponse.json(
        { success: false, message: '未提供项目ID' },
        { status: 400 }
      );
    }

    // 验证用户是否有权限查看邀请
    const userRole = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId,
          userId: session.user.id,
          role: {
            in: ['OWNER', 'ADMIN'],
          },
        },
      });
    });

    if (!userRole.success || !userRole.data) {
      return NextResponse.json(
        { success: false, message: '您没有权限查看项目邀请' },
        { status: 403 }
      );
    }

    // 获取未过期的项目邀请
    const invites = await dbOperation(async () => {
      return prisma.projectInvite.findMany({
        where: {
          projectId,
          expires: {
            gt: new Date(), // 只获取未过期的邀请
          },
          acceptedAt: null, // 只获取未接受的邀请
        },
        orderBy: {
          createdAt: 'desc',
        },
        include: {
          inviter: {
            select: {
              id: true,
              name: true,
              email: true,
              image: true,
            },
          },
        },
      });
    });

    if (!invites.success) {
      return NextResponse.json(
        { success: false, message: '获取项目邀请失败', error: invites.error },
        { status: 500 }
      );
    }

    // 确保invites.data存在
    if (!invites.data) {
      return NextResponse.json(
        { success: true, data: [] }
      );
    }

    // 格式化返回数据
    const formattedInvites = invites.data.map((invite) => ({
      id: invite.id,
      email: invite.email,
      role: invite.role,
      message: invite.message,
      expires: invite.expires,
      createdAt: invite.createdAt,
      status: invite.acceptedAt ? 'ACCEPTED' : 'PENDING',
      token: invite.token,
      inviter: {
        id: invite.inviter.id,
        name: invite.inviter.name,
        email: invite.inviter.email,
        image: invite.inviter.image,
      },
    }));

    return NextResponse.json({ success: true, data: formattedInvites });
  } catch (error: any) {
    console.error('获取项目邀请失败:', error);
    return NextResponse.json(
      { success: false, message: '获取项目邀请失败', error: error.message },
      { status: 500 }
    );
  }
}

// 删除项目邀请
export async function DELETE(request: NextRequest) {
  try {
    // 检查用户是否已认证
    const session = await auth();

    if (!session?.user) {
      return NextResponse.json(
        { success: false, message: '未授权访问' },
        { status: 401 }
      );
    }

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams;
    const inviteId = searchParams.get('id');

    if (!inviteId) {
      return NextResponse.json(
        { success: false, message: '未提供邀请ID' },
        { status: 400 }
      );
    }

    // 获取邀请详情
    const invite = await dbOperation(async () => {
      return prisma.projectInvite.findUnique({
        where: {
          id: inviteId,
        },
      });
    });

    if (!invite.success || !invite.data) {
      return NextResponse.json(
        { success: false, message: '邀请不存在', error: invite.error },
        { status: 404 }
      );
    }

    // 验证用户是否有权限删除邀请
    const userRole = await dbOperation(async () => {
      return prisma.projectUser.findFirst({
        where: {
          projectId: invite.data.projectId,
          userId: session.user.id,
          role: {
            in: ['OWNER', 'ADMIN'],
          },
        },
      });
    });

    if (!userRole.success || !userRole.data) {
      return NextResponse.json(
        { success: false, message: '您没有权限删除此邀请' },
        { status: 403 }
      );
    }

    // 删除邀请
    const deleteInvite = await dbOperation(async () => {
      return prisma.projectInvite.delete({
        where: {
          id: inviteId,
        },
      });
    });

    if (!deleteInvite.success) {
      return NextResponse.json(
        { success: false, message: '删除邀请失败', error: deleteInvite.error },
        { status: 500 }
      );
    }

    return NextResponse.json({ success: true, message: '邀请删除成功' });
  } catch (error: any) {
    console.error('删除项目邀请失败:', error);
    return NextResponse.json(
      { success: false, message: '删除项目邀请失败', error: error.message },
      { status: 500 }
    );
  }
} 
